<template>
    <div class="layout">
        <Layout>
            
            <Sider class="sidebar" ref="side1" :width=256   hide-trigger  >
                    <Menu  ref="sideBarMenu"   
                        :theme="theme2"
                        width="auto"  
                        accordion 
                        :open-names="openNames"
                        :active-name="activeMenuItem" 
                        @on-select="menuItemSelect"  
                        @on-open-change="openChange"  
                    >

                        <!-- 只支持三级菜单 四级需要继续添加for if 之类的 -->
                        <Submenu v-for="item in menuTree" :key="item.name" :name="item.name" >
                            <template slot='title'><Icon :type="item.icon"/>{{ item.name }}</template>  <!-- 1级 集群管理-->
                            <!-- sitem代表二级  -->
                            <template v-for="sitem in item.children">
                                <Submenu v-if="sitem.children && sitem.children.length != 0" :name="sitem.name" :key="sitem.name" >
                                    <template slot='title'>{{ sitem.name }}</template>  <!-- 2级 集群信息-->
                                    <!-- 遍历叶子结点 titem代表三级 -->
                                    <MenuItem  v-for="titem in sitem.children" :key="titem.name" :name="titem.name" :to="{name: titem.to}">{{titem.name}}</MenuItem> <!-- 3级 创建集群-->
                                </Submenu>
                                <!-- 叶子结点 -->
                                <MenuItem v-else :name="sitem.name" :key="sitem.name" :to="{name: sitem.to}">{{sitem.name}}</MenuItem><!-- 2级 节点信息-->
                            </template>
                        </Submenu>

                    </Menu>

            </Sider>
            <Layout>
                <Header :style="{padding: 0}" class="layout-header-bar">
                    <div style="float: left;margin: 0 20px;" >
                        <template v-if="sharedState.clusterList.length != 0 && $route.meta.k8s" >
                            <span>集群: </span>
                            <Select  v-model="sharedState.clusterName" style="width:200px;margin-right: 10px" @on-change="changeCluster()">
                                <template v-for="cluster in sharedState.clusterList" >
                                    <Option  :key="cluster" :value="cluster" v-if="cluster === 'sharedState.clusterName' "  selected>{{ cluster }}</Option>
                                    <Option :key="cluster" :value="cluster" v-else>{{ cluster }} </Option>
                                </template>
                            </Select>
                        </template>
                         <template v-if="sharedState.namespaceList.length != 0 && $route.meta.namespace" >
                            <span>命名空间: </span>
                            <Select v-model="sharedState.namespace" style="width:250px" @on-change="changeNamespace()">
                                <template v-for="namespace in sharedState.namespaceList" >
                                    <Option  :key="namespace" :value="namespace" v-if="namespace === 'sharedState.namespace' "  selected>{{ namespace }}</Option>
                                    <Option :key="namespace" :value="namespace" v-else>{{ namespace }} </Option>
                                </template>
                                <Option value="all">all</Option>
                            </Select>
                        </template>
                        <!-- es集群 -->
                        <template v-if="sharedState.esClusterList.length != 0 && $route.meta.es" >
                            <span>集群: </span>
                            <Select  v-model="sharedState.esClusterName" style="width:200px;margin-right: 10px" @on-change="changeEsCluster()">
                                <template v-for="cluster in sharedState.esClusterList" >
                                    <Option  :key="cluster" :value="cluster" v-if="cluster === 'sharedState.esClusterName' "  selected>{{ cluster }}</Option>
                                    <Option :key="cluster" :value="cluster" v-else>{{ cluster }} </Option>
                                </template>
                            </Select>
                        </template>
                        <!-- {{ $route.name }} -->

                    </div>
                    <div class="header-right">
                        <Dropdown>
                            <a href="javascript:void(0)">
                                {{ username }}
                                <Icon type="ios-arrow-down"></Icon>
                            </a>
                            <DropdownMenu slot="list">
                                <DropdownItem><a @click="logout">退出</a></DropdownItem>
                            </DropdownMenu>
                        </Dropdown>
                    </div>
                </Header>
                <Content :style="{margin: '10px', background: '#fff', minHeight: '841px'}">
                    <!-- <Row>
                        <div style="margin:5px">
                            <Breadcrumb>
                                <BreadcrumbItem :to="route_path">{{route_path}}</BreadcrumbItem>
                            </Breadcrumb>
                        </div>
                    </Row> -->
                    <Row>
                         <router-view v-if="isRouterAlive" ></router-view>
                    </Row>
                   
                </Content>
            </Layout>
        </Layout>
    </div>
</template>
<script>
    import store from '@/store';
    import axios from 'axios';
    import { get_namespace_name_list,get_user_resource } from '@/api'
    export default {
        name: 'Home',
        data () {
            return {
                // isCollapsed: false,
                username: '',
                theme2: 'dark',
                sharedState: store.state,
                // 激活的左侧菜单栏
                activeMenuItem: '',
                // 激活的子菜单
                openNames:[],
                // 集群、命名空间改变刷新页面
                isRouterAlive: false,
                menuTree: [],

                // 面包屑
                route_path: '',
            }
        },
        methods: {
            logout() {
                localStorage.removeItem("username");
                localStorage.removeItem("token");
                this.$router.push('/login')
            },
            //
            async changeEsCluster(){
                let cluster = this.sharedState.esClusterName
                localStorage.setItem('currentEsCluster',cluster)
                // 刷新页面
                this.isRouterAlive = false
                this.$nextTick(function () {
                    this.isRouterAlive = true
                })
            },
            // 集群Select改变事件
            async changeCluster(){
                let cluster = this.sharedState.clusterName;
                if(cluster){
                    localStorage.setItem('currentCluster',cluster)
                    let namespace_list  = await this.getNamespaceList(cluster)
                    if(namespace_list == null) {
                        alert('changeCluster连接不上集群,获取不到命名空间信息')
                        return
                    }else{
                        if(namespace_list.length > 0){
                            let currentNameSpace = localStorage.getItem('currentNameSpace')
                            if(namespace_list.indexOf(currentNameSpace) != -1  || currentNameSpace ==='all'){
                                store.setNamespace(currentNameSpace)
                            }else {
                                localStorage.setItem('currentNameSpace',namespace_list[0])
                                store.setNamespace(namespace_list[0])
                            }
                            store.setNamespaceList(namespace_list)
                        }
                    }
                    // 刷新页面
                    this.isRouterAlive = false
                    this.$nextTick(function () {
                        this.isRouterAlive = true
                    })
                }
                
            },
            // 命名空间改变事件
            changeNamespace(){
                let namespace = this.sharedState.namespace
                if(namespace){
                    localStorage.setItem('currentNameSpace',namespace)
                }
                // 刷新页面
                this.isRouterAlive = false
                this.$nextTick(function () {
                    this.isRouterAlive = true
                })
            },

            async  getNamespaceList(cluster_name) {
                try {
                    let response = await axios({
                        method: 'post',
                        url: get_namespace_name_list,
                        headers: {'cluster_name':cluster_name},
                        timeout: 30000,
                    })
                    if(response.data.status==500) {
                        this.$Message.error('获取不到命名空间信息')
                        return null
                    }
                    return response.data;
                } catch (error) {
                    this.$Message.error("请求异常："+error);
                    return null;
                }
            },

            // 左侧菜单栏选择事件
            menuItemSelect(name){
                // 设置选中的菜单项
                this.activeMenuItem = name
                localStorage.setItem("activeMenuItem",name)
            },
            // 子菜单展开收起事件
            openChange(name) {
                this.openNames=name
                localStorage.setItem("openNames",name)
            },
            // 获取用户资源
            async getUserResource() {
                try {
                    let token = localStorage.getItem("token")
                    let username = localStorage.getItem("username")
                    let headers = {"token":token,"username":username}
                    let response = await axios({
                        method: 'post',
                        url: get_user_resource,
                        headers: headers,
                    })
                    if(response.data.status==500) {
                        this.$Message.error('获取不到资源信息')
                        return null
                    }
                    // 目前返回的只有菜单，以后可能会添加功能
                    this.menuTree = response.data.menu_list 
                    let op_list = response.data.op_list
                    let op_code_list  = []
                    for(let i=0;i<op_list.length;i++){
                        let op_code = op_list[i]['code']
                        op_code_list.push(op_code)
                    }
                    sessionStorage.setItem('operation_list',JSON.stringify(op_code_list))
                } catch (error) {
                    this.$Message.error("请求异常："+error);
                    return null;
                }
            },
            openParentMenu(){
                let openNames = localStorage.getItem("openNames")
                if(openNames){
                    this.openNames = []
                    let open_list = openNames.split(',')
                    for(let i=0;i<open_list.length;i++)
                        this.openNames.push(open_list[i])
                    setTimeout(() =>{
                        this.$refs.sideBarMenu.updateOpened();
                    },500);
                }else{
                    this.openNames = []
                }
            },
            activeLeafMenu(){
                let activeMenuItem = localStorage.getItem("activeMenuItem")
                if(activeMenuItem){
                    this.activeMenuItem = activeMenuItem
                    setTimeout(() =>{
                        this.$refs.sideBarMenu.updateActiveName();
                    },500);
                }else{
                    this.activeMenuItem = ''
                }
            },
        },

        created: async function() {
            await this.getUserResource()
        },

        mounted: function() {
            // console.log(this.$route)
            let tableHeight = localStorage.getItem("tableHeight")
            if(tableHeight != undefined || tableHeight != null) {
                store.setTabelHeight(tableHeight)
            }

            this.route_path = this.$route.path
            this.openParentMenu()
            this.activeLeafMenu()
            let username = localStorage.getItem('username')
            if(username) {
                this.username = username
            }else {
                this.username = '匿名'
            }
            // 解决首页显示 《写笔记》清空数据后，不显示
            setTimeout(() =>{
                this.isRouterAlive = true
            },500);
            

        },
        watch:{
            '$route.path':function(to,from){
                console.log(to+"---"+from);
                this.route_path = to
            }
        }

    }
</script>
<style >
    .ivu-layout-content {
        min-height: 947px !important; 
    }
    body {
        overflow-x: auto;
        overflow-y: hidden;
    } 
</style>
<style scoped>
    .layout{
        border: 1px solid #d7dde4;
        background: #f5f7f9;
        position: relative;
        border-radius: 4px;
        overflow-x: auto;
        overflow-y: hidden;
    }
    .layout-header-bar{
        height: 55px;
        background: #fff;
        box-shadow: 0 1px 1px rgba(0,0,0,.1);
    }
    .layout-nav{
        width: 300px;
        margin: 0 auto;
        margin-right: 10px;
    }
    .menu-item i{
        transform: translateX(0px);
        transition: font-size .2s ease, transform .2s ease;
        vertical-align: middle;
        font-size: 16px;
    }
    .header-right {
        position: absolute;
        right: 0;
        margin-right: 25px;
    } 
    .sidebar {
        font-family:Arial, Helvetica, sans-serif;
        /* height: 920px; */
        height: calc(100vh - 10px);
        overflow-y: scroll;
    }
    ::-webkit-scrollbar-track {
        background-color: white;
    }
    ::-webkit-scrollbar {
        width: 5px;
    }
    ::-webkit-scrollbar-thumb {
        background-color: white;
        border-radius: 50%;
    }
    body {
        overflow-x: auto;
        overflow-y: hidden;
    } 
</style>
